package controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import entity.StorageRecord;
import entity.Supplier;
import entity.SysUser;
import service.StorageRecordService;
import service.SupplierService;
import utils.Constants;
import utils.Page;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/main/storageRecord")
public class StorageRecordController extends BaseController {

    private static final Logger LOGGER =
            LoggerFactory.getLogger(StorageRecordController.class);
    @Autowired
    private StorageRecordService storageRecordService;
    @Autowired
    private SupplierService supplierService;

    @RequestMapping("/page")
    public String page(Model model, StorageRecord condition,
                       @RequestParam(value = "pageNo", defaultValue = "1") Integer pageNo,
                       @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize){
        Page<StorageRecord> page = null;
        try {
            // 查询用户的分页信息
            page = storageRecordService.getPage(condition, pageNo, pageSize);
            List<Supplier> supplierList = supplierService.getSuppliers();
            // 将分页数据、角色列表和查询条件设置到模型数据中
            model.addAttribute("pageInfo", page);
            model.addAttribute("supplierList", supplierList);
            model.addAttribute("condition", condition);
        } catch (Exception e) {
            LOGGER.error("SysUserController 中的 page 方法执行发生错误。 ", e);
            throw new RuntimeException(e);
        }
        return "storageRecord/page";
    }

    @GetMapping("/save")
    public String toSave(Model model) {
        List<Supplier> supplierList = null;
        try {
            supplierList = supplierService.getSuppliers();
            // 有角色下拉框需要数据
            model.addAttribute("supplierList", supplierList);
            // 回显数据时需要 sysUser，这里给个空对象避免出错
            model.addAttribute("storageRecord", new StorageRecord());
        } catch (Exception e) {
            LOGGER.error("SysUserController中的toSave方法执行发生错误。", e);
            throw new RuntimeException(e);
        }
        return "storageRecord/save";
    }

    @PostMapping("/save")
    public String doSave(StorageRecord storageRecord) {
        try {
            // 通过父类的 session 方法获取登录用户，由于泛型自动转换无需强转
            SysUser loginUser = session(Constants.SESSION_USER);
            boolean ok = false;
            if (storageRecord.getId() == null) {
                // 如果是添加用户，关联创建用户为当前登陆用户
                storageRecord.setCreatedUserId(loginUser.getId());
                storageRecord.setCreatedTime(new Date());
                ok = storageRecordService.add(storageRecord);
            } else {
                // 如果是修改用户，关联修改用户为当前登陆用户
                storageRecord.setUpdatedUserId(loginUser.getId());
                storageRecord.setUpdatedTime(new Date());
                ok = storageRecordService.update(storageRecord);
            }
            if (ok) {
                // 保存成功，跳回列表页面
                return redirect("/main/storageRecord/page");
            }
        } catch (Exception e) {
            LOGGER.error("SysUserController中的doSave方法执行发生错误。", e);
            throw new RuntimeException(e);
        }
        return "storageRecord/save";

    }
    @GetMapping("/view/{id}")
    public String view(@PathVariable("id") Long id, Model model){
        StorageRecord storageRecord = null;
        try {
            storageRecord = storageRecordService.getById(id);
            model.addAttribute("storageRecord", storageRecord);
        } catch (Exception e) {
            LOGGER.error("SysUserController 中的 view 方法执行发生错误。 ", e);
            throw new RuntimeException(e);
        }
        return "storageRecord/view";
    }

    @DeleteMapping("/del/{id}")
    @ResponseBody
    public Object del(@PathVariable("id") Integer id, Model model){
        Map<String,Object> map = new HashMap<>();
        try {
            int num = storageRecordService.delete(id);
            if (num > 0) {
                map.put("code",200);
                map.put("msg","删除成功");
            }
        } catch (Exception e) {
            LOGGER.error("SysUserController 中的 view 方法执行发生错误。 ", e);
            throw new RuntimeException(e);
        }
        return map;
    }

    /**
     * 查询用户信息并跳转修改页（共用 save.jsp)
     */
    @GetMapping("/edit")
    public String toEdit(@RequestParam("id") Long id, Model model) {
        StorageRecord storageRecord = null;
        List<Supplier> supplierList = null;
        try {
            supplierList = supplierService.getSuppliers();
            // 有角色下拉框需要数据
            model.addAttribute("supplierList", supplierList);
            storageRecord = storageRecordService.getById(id);
            // 回显数据时需要 sysUser，这里给个空对象避免出错
            model.addAttribute("storageRecord", storageRecord);
        } catch (Exception e) {
            LOGGER.error("SysUserController 中的 toEdit 方法执行发生错误。 ", e);
            throw new RuntimeException(e);
        }return "storageRecord/save";
    }

    @ResponseBody
    @GetMapping("/srCodeExist")
    public Object srCodeExist(@RequestParam("srCode") String srCode){
        Map<String, Object> map = new HashMap<>();
        try{
            // 角色编号不可为空
            if(StringUtils.isEmpty(srCode)){
                map.put("exist", 0);
            }else {
                StorageRecord storageRecord = storageRecordService.getSrCode(srCode);
                if(null != storageRecord) {
                    map.put("exist", 1);
                }else {
                    map.put("exist", 0);
                }
            }
        }catch (Exception e){
            LOGGER.error("SysUserController中的accountExists方法执行发生错误", e);
            map.put("error", "出现异常，请联系管理员处理！ ");
        }
        return map;
    }
}
